import { App } from 'vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { isArray } from '@/utils/is'

const { t } = useI18n()

export function hasPerm(app: App<Element>) {
  app.directive('hasPerm', (el, binding) => {
    const { wsCache } = useCache()
    const { value: permissionFlag } = binding
    const all_permission = '*:*:*'
    const permissions = wsCache.get(CACHE_KEY.USER).permissions

    if (permissionFlag && isArray(permissionFlag) && permissionFlag.length > 0) {
      const hasPermissions = permissions.some((permission: string) => {
        return all_permission === permission || permissionFlag.includes(permission)
      })

      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(t('permission.hasPermission'))
    }
  })
}
